package com.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.domain.UserMoments;
import com.mapper.UserMomentsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserMomentsServiceImpl {

    @Autowired
    private UserMomentsDao userMomentsDao;

    /**
     * 整个SpringBoot应用的上下文，通过它可以获取整个应用全部的 bean (例如MQ的生产者)
     */
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    public void addUserMoments(UserMoments userMoments) throws Exception {
        userMoments.setCreateTime(new Date());
        userMomentsDao.addUserMoments(userMoments);
//        DefaultMQProducer producer = applicationContext.getBean(RocketMQConfig.MOMENTS_PRODUCER, DefaultMQProducer.class);
//        byte[] body = JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8);
//        Message msg = new Message(UserMomentConstant.TOPIC_MOMENTS, body);
//        //异步发布消息
//        RocketMQUtil.asyncSendMsg(producer, msg);
    }


    public List<UserMoments> getUserSubscribedMoments(Long userId) {
        String key = "subscribed-" + userId;
        //从 redis 中获取 userId 订阅的动态信息
        String listStr = redisTemplate.opsForValue().get(key);
        return JSONArray.parseArray(listStr, UserMoments.class);
    }
}
